#include "MGCApplication.h"


#include "MGCToolbox.h"
#include "MGCCorePlugin.h"

#include "QmlControls/MGroundControlQmlGlobal.h"
#include "QmlControls/ScreenToolsController.h"

#include "QGCMapEngine.h"
#include "MGCPalette.h"

MGCApplication* MGCApplication::_app = nullptr;

static QObject* screenToolsControllerSingletonFactory(QQmlEngine*, QJSEngine*)
{
    ScreenToolsController* screenToolsController = new ScreenToolsController;
    return screenToolsController;
}

static QObject* mgroundcontrolQmlGlobalSingletonFactory(QQmlEngine*,QJSEngine*)
{
    MGroundControlQmlGlobal* qmlGlobal = new MGroundControlQmlGlobal(qgcApp(),qgcApp()->toolbox());
    qmlGlobal->setToolbox(qgcApp()->toolbox());
    return qmlGlobal;
}

MGCApplication::MGCApplication(int &argc, char* argv[])
    : QApplication(argc, argv)
{
    _app = this;

    _toolbox = new MGCToolbox(this);
    _toolbox->setChildToolboxes();
}

void MGCApplication::_initCommon()
{
    qmlRegisterType<MGCPalette>("MGroundControl.Palette", 1, 0, "MGCPalette");
    qmlRegisterType<ScreenToolsController>("MGroundControl.ScreenToolsController",1,0,"ScreenToolsController");

    qmlRegisterSingletonType<MGroundControlQmlGlobal>("MGroundControl",1,0,"MGroundControl",mgroundcontrolQmlGlobalSingletonFactory);
    qmlRegisterSingletonType<ScreenToolsController>  ("MGroundControl.ScreenToolsController",    1, 0, "ScreenToolsController",  screenToolsControllerSingletonFactory);

}


MGCToolbox *MGCApplication::toolbox() const
{
    return _toolbox;
}


bool MGCApplication::_initForNormalAppBoot()
{
    _qmlAppEngine = toolbox()->corePlugin()->createQmlApplicationEngine(this);
    toolbox()->corePlugin()->createRootWindow(_qmlAppEngine);

    getQGCMapEngine()->wasCacheReset();

    return true;
}

MGCApplication *qgcApp()
{
    return MGCApplication::_app;
}
